package vip.zhenzicheng.bio;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.logging.Logger;

/**
 * BIO 通信客户端
 *
 * @author zhenzicheng
 * @date: 2022-06-01 14:31
 */
public class Client {
  private static final Logger LOG = Logger.getLogger(Client.class.getSimpleName());

  public static void main(String[] args) throws IOException {
    // 客户端启动
    Socket socket = null;
    // 实例化与服务端通信的输入输出流
    ObjectOutputStream output = null;
    ObjectInputStream input = null;
    // 服务器通信地址
    // InetSocketAddress address = new InetSocketAddress("127.0.0.1", 8888);
    InetSocketAddress address = new InetSocketAddress("127.0.0.1", 10001);
    try {
      socket = new Socket();
      socket.connect(address);
      LOG.info("Connect Server success!");
      output = new ObjectOutputStream(socket.getOutputStream());
      input = new ObjectInputStream(socket.getInputStream());
      LOG.info("Ready send message......");
      // 向服务器输出请求
      output.writeUTF("oh yes! Hello World!");
      output.flush();

      // 接收服务器的输出
      LOG.info(input.readUTF());
    } finally {
      if (socket != null) {
        socket.close();
      }
      if (output != null) {
        output.close();
      }
      if (input != null) {
        input.close();
      }
    }
  }
}
